<template>
  <div class="user-center-container">
    <CallBack />
    <div class="user-center-content">
      <el-tabs v-model="activeTab" class="user-tabs">
        <el-tab-pane :label="t('personal_info')" name="profile">
          <div class="user-profile-section">
            <div class="avatar-section">
              <div class="avatar-container">
                <span class="user-avatar">👤</span>
              </div>
              <div class="user-info">
                <h2> {{ t('user_prefix') }} : {{ userInfo.nickname }}</h2>
                <p class="user-status" v-if="userStore.getPremiumStatus">
                  <span class="premium-icon">👑</span>
                  <span>{{ t('premium_member') }}</span>
                </p>
              </div>
            </div>
            
            <div class="info-items">
              <div class="info-item">
                <span class="info-label">{{ t('phone') }} : </span>
                <span class="info-value">{{ userInfo.phone || t('not_bound') }}</span>
                <el-button 
                  v-if="!userInfo.phone" 
                  size="small" 
                  type="primary"
                  @click="showBindPhoneDialog"
                >{{ t('bind_phone_number') }}</el-button>
              </div>
              
              <div class="info-item">
                <span class="info-label">{{ t('email') }} : </span>
                <span class="info-value">{{ userInfo.email || t('not_bound') }}</span>
                <el-button 
                  v-if="!userInfo.email" 
                  size="small" 
                  type="primary"
                  @click="showBindEmailDialog"
                >{{ t('bind_email') }}</el-button>
              </div>
              <div class="info-item">
                <span class="info-label">{{ t('registration_time') }} : </span>
                <span class="info-value">{{ userInfo.registerTime || t('unknown') }}</span>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane :label="t('consultation_history')" name="history">
          <div class="history-section">
            <div class="search-bar">
              <el-input 
                v-model="searchKeyword" 
                :placeholder="t('please_input_keywords')" 
                clearable
                class="search-input"
              />
              <el-button type="primary" @click="searchHistory">{{ t('search') }}</el-button>
            </div>
            
            <div class="history-list">
              <div 
                v-for="(item, index) in historyList" 
                :key="index" 
                class="history-item"
                @click="viewHistoryDetail(item)"
              >
                <div class="history-icon">
                  <el-icon><Document /></el-icon>
                </div>
                <div class="history-content">
                  <div class="history-title" :class="{'text-red': item.esey === 1, 'text-blue': item.esey !== 1}">
                    {{ t('consultation_number') }}: {{ item.id }}
                  </div>
                  <div class="history-desc">{{ t(item.msg_title) }}</div>
                </div>
              </div>
              
              <div class="load-more" v-if="showMoreButton">
                <el-button type="primary" @click="loadMoreHistory">{{ t('load_more') }}</el-button>
              </div>
              
              <div class="empty-data" v-if="historyList.length === 0">
                <el-empty :description="t('no_data')" />
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <el-tab-pane :label="t('security_settings')" name="security">
          <div class="security-section">
            <div class="security-item">
              <div class="security-info">
                <h3>{{ t('change_password') }}</h3>
                <p>{{ t('regular_password_change') }}</p>
              </div>
              <el-button type="primary" @click="showChangePasswordDialog">{{ t('change_password') }}</el-button>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- 绑定手机号对话框 -->
    <el-dialog
      v-model="bindPhoneDialogVisible"
      :title="t('bind_phone_number')"
      :width="isMobile ? '90%' : '400px'"
      class="responsive-dialog"
    >
      <div class="bind-form">
        <el-form :model="bindPhoneForm" label-width="80px">
          <el-form-item label="手机号">
            <el-input v-model="bindPhoneForm.phone" placeholder="请输入手机号" maxlength="11" />
          </el-form-item>
          <el-form-item label="验证码">
            <div class="verification-code-group">
              <el-input v-model="bindPhoneForm.code" placeholder="请输入验证码" maxlength="6" />
              <el-button 
                class="verification-code-btn" 
                @click="sendVerificationCode('phone')"
                :disabled="!isPhoneValid(bindPhoneForm.phone) || phoneCooldown > 0"
                :class="{ 'cooldown': phoneCooldown > 0 }"
              >
                {{ phoneCooldown > 0 ? `${phoneCooldown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="bindPhoneDialogVisible = false">{{ t('cancel') }}</el-button>
          <el-button type="primary" @click="bindPhone" :disabled="!canBindPhone">{{ t('confirm_change') }}</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 绑定邮箱对话框 -->
    <el-dialog
      v-model="bindEmailDialogVisible"
      :title="t('bind_email')"
      :width="isMobile ? '90%' : '400px'"
      class="responsive-dialog"
    >
      <div class="bind-form">
        <el-form :model="bindEmailForm" label-width="80px">
          <el-form-item label="邮箱">
            <el-input v-model="bindEmailForm.email" placeholder="请输入邮箱地址" />
          </el-form-item>
          <el-form-item label="验证码">
            <div class="verification-code-group">
              <el-input v-model="bindEmailForm.code" placeholder="请输入验证码" maxlength="6" />
              <el-button 
                class="verification-code-btn" 
                @click="sendVerificationCode('email')"
                :disabled="!isEmailValid(bindEmailForm.email) || emailCooldown > 0"
                :class="{ 'cooldown': emailCooldown > 0 }"
              >
                {{ emailCooldown > 0 ? `${emailCooldown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="bindEmailDialogVisible = false">{{ t('cancel') }}</el-button>
          <el-button type="primary" @click="bindEmail" :disabled="!canBindEmail">{{ t('confirm_change') }}</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      :title="t('change_password')"
      :width="isMobile ? '90%' : '400px'"
      class="responsive-dialog"
    >
      <div class="bind-form password-form">
        <el-form :model="passwordForm" label-position="top">
          <el-form-item :label="t('new_password')" class="password-form-item">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              :placeholder="t('please_input_new_password')" 
              show-password 
              class="password-input"
            />
          </el-form-item>
          <el-form-item :label="t('confirm_new_password')" class="password-form-item">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              :placeholder="t('please_retype_new_password')" 
              show-password 
              class="password-input"
            />
          </el-form-item>
        </el-form>
        <div class="dialog-footer password-dialog-footer">
          <el-button 
            @click="changePasswordDialogVisible = false" 
            class="password-btn cancel-btn"
          >{{ t('cancel') }}</el-button>
          <el-button 
            type="primary" 
            @click="handleChangePassword" 
            :disabled="!canChangePassword" 
            class="password-btn confirm-btn"
          >{{ t('confirm_change') }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="UserCenter">
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/userStore';
import { sendSmsCode } from '@/api/login';
import request from '@/utils/request';
import { Document } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { useLanguageStore } from '@/store/languageStore';
import CallBack from '@/components/common/CallBack.vue';
const { t } = useLanguageStore();
// 获取用户信息
const userStore = useUserStore();
const router = useRouter();
const activeTab = ref('profile');

// 检测是否为移动设备
const isMobile = ref(window.innerWidth <= 768);

// 监听窗口尺寸变化
const handleResize = () => {
  isMobile.value = window.innerWidth <= 768;
};

window.addEventListener('resize', handleResize);

// 组件卸载时移除事件监听
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

// 用户信息
const userInfo = reactive({
  nickname: userStore.getUserName.username || '用户',
  phone: '',
  email: '',
  registerTime: ''
});

// 获取用户详细信息
const fetchUserInfo = async () => {
  try {
    const res = await request({
      url: '/v6/user/info',
      method: 'get'
    });
    
    if (res.code === 0 && res.data) {
      userInfo.nickname = res.data.nickname || userStore.getUserName.username || res.data.id;
      userInfo.phone = res.data.phone || '';
      userInfo.email = res.data.email || '';
      userInfo.registerTime = res.data.create_time || '';
      userInfo.sex = res.data.sex || 0;
      userInfo.birth = res.data.birth || '';
      
      // 更新会员卡信息
      userInfo.once_nums = res.data.once_nums || 0;
      userInfo.month_day = res.data.month_day || 0;
      userInfo.works_once_nums = res.data.works_once_nums || 0;
      userInfo.works_month_nums = res.data.works_month_nums || 0;
      userInfo.emotion_once_nums = res.data.emotion_once_nums || 0;
      userInfo.emotion_month_nums = res.data.emotion_month_nums || 0;
      userInfo.pr_once_nums = res.data.pr_once_nums || 0;
      userInfo.pr_month_nums = res.data.pr_month_nums || 0;
      userInfo.group_once_nums = res.data.group_once_nums || 0;
      userInfo.group_month_nums = res.data.group_month_nums || 0;
      userInfo.stu_once_nums = res.data.stu_once_nums || 0;
      userInfo.stu_month_nums = res.data.stu_month_nums || 0;
      userInfo.medical_once_nums = res.data.medical_once_nums || 0;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
  }
};

// 绑定手机号相关
const bindPhoneDialogVisible = ref(false);
const bindPhoneForm = reactive({
  phone: '',
  code: ''
});
const phoneCooldown = ref(0);

const showBindPhoneDialog = () => {
  bindPhoneDialogVisible.value = true;
};

const canBindPhone = computed(() => {
  return isPhoneValid(bindPhoneForm.phone) && bindPhoneForm.code.length === 6;
});

const bindPhone = async () => {
  if (!canBindPhone.value) return;
  
  try {
    const res = await request({
      url: '/v6/user/bindPhone',
      method: 'post',
      data: {
        phone: bindPhoneForm.phone,
        code: bindPhoneForm.code
      }
    });
    
    if (res.code === 0) {
      ElMessage.success('手机号绑定成功');
      userInfo.phone = bindPhoneForm.phone;
      bindPhoneDialogVisible.value = false;
      // 重置表单
      bindPhoneForm.phone = '';
      bindPhoneForm.code = '';
    } else {
      ElMessage.error(res.msg || '绑定失败，请重试');
    }
  } catch (error) {
    console.error('绑定手机号失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

// 绑定邮箱相关
const bindEmailDialogVisible = ref(false);
const bindEmailForm = reactive({
  email: '',
  code: ''
});
const emailCooldown = ref(0);

const showBindEmailDialog = () => {
  bindEmailDialogVisible.value = true;
};

const canBindEmail = computed(() => {
  return isEmailValid(bindEmailForm.email) && bindEmailForm.code.length === 6;
});

const bindEmail = async () => {
  if (!canBindEmail.value) return;
  
  try {
    const res = await request({
      url: '/v6/user/bindEmail',
      method: 'post',
      data: {
        email: bindEmailForm.email,
        code: bindEmailForm.code
      }
    });
    
    if (res.code === 0) {
      ElMessage.success('邮箱绑定成功');
      userInfo.email = bindEmailForm.email;
      bindEmailDialogVisible.value = false;
      // 重置表单
      bindEmailForm.email = '';
      bindEmailForm.code = '';
    } else {
      ElMessage.error(res.msg || '绑定失败，请重试');
    }
  } catch (error) {
    console.error('绑定邮箱失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

import { changePassword } from '@/api/user';

// 修改密码相关
const changePasswordDialogVisible = ref(false);
const passwordForm = reactive({
  newPassword: '',
  confirmPassword: ''
});

const showChangePasswordDialog = () => {
  changePasswordDialogVisible.value = true;
};

const canChangePassword = computed(() => {
  return (
    passwordForm.newPassword.length >= 6 && 
    passwordForm.newPassword === passwordForm.confirmPassword
  );
});

const handleChangePassword = async () => {
  if (!canChangePassword.value) return;
  
  try {
    const res = await changePassword({
      new_password: passwordForm.newPassword
    });
    
    if (res.code === 0) {
      ElMessage.success('密码修改成功');
      changePasswordDialogVisible.value = false;
      // 重置表单
      passwordForm.newPassword = '';
      passwordForm.confirmPassword = '';
    } else {
      ElMessage.error(res.msg || '修改失败，请重试');
    }
  } catch (error) {
    console.error('修改密码失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

// 发送验证码
const sendVerificationCode = async (type) => {
  let account = '';
  let cooldownRef = null;
  
  if (type === 'phone') {
    account = bindPhoneForm.phone;
    cooldownRef = phoneCooldown;
  } else if (type === 'email') {
    account = bindEmailForm.email;
    cooldownRef = emailCooldown;
  }
  
  if (!account) return;
  
  try {
    const res = await sendSmsCode({ phone: account });
    
    if (res.code === 0) {
      ElMessage.success('验证码已发送');
      // 开始倒计时
      cooldownRef.value = 60;
      const timer = setInterval(() => {
        cooldownRef.value--;
        if (cooldownRef.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg || '发送验证码失败');
    }
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

// 验证手机号和邮箱格式
const isPhoneValid = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone);
};

const isEmailValid = (email) => {
  return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(email);
};

// 询问历史相关
const historyList = ref([]);
const searchKeyword = ref('');
const currentPage = ref(1);
const showMoreButton = ref(true);

// 获取询问历史
const fetchHistoryList = async (page = 1, keyword = '') => {
  try {
    const res = await request({
      url: '/v6/user/history',
      method: 'post',
      data: {
        page,
        title: keyword
      }
    });
    
    if (res.code === 0 && res.data) {
      if (page === 1) {
        historyList.value = res.data.data || [];
      } else {
        historyList.value = [...historyList.value, ...(res.data.data || [])];
      }
      
      // 判断是否还有更多数据
      if (res.data.current_page >= res.data.last_page) {
        showMoreButton.value = false;
      } else {
        showMoreButton.value = true;
      }
      
      currentPage.value = page;
    } else {
      ElMessage.error(res.msg || '获取询问历史失败');
    }
  } catch (error) {
    console.error('获取询问历史失败:', error);
    ElMessage.error('网络错误，请重试');
  }
};

// 搜索历史
const searchHistory = () => {
  fetchHistoryList(1, searchKeyword.value);
};

// 加载更多历史
const loadMoreHistory = () => {
  fetchHistoryList(currentPage.value + 1, searchKeyword.value);
};

// 查看历史详情
const viewHistoryDetail = (item) => {
  // 跳转到历史详情页面
  router.push({
    path: '/history-detail',
    query: {
      history_id: item.history_id,
      answer_id: item.answer_id,
      person_menu_id: item.person_menu_id,
      person_menu_item_id: item.person_menu_item_id,
      is_show_time_res: item.is_show_time_res
    }
  });
};

// 页面加载时获取用户信息和询问历史
onMounted(() => {
  fetchUserInfo();
  fetchHistoryList();
});
</script>

<style scoped lang="less">
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px 15px;
}

.user-center-header {
  margin-bottom: 30px;
}

.user-center-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.user-tabs {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 20px;
  
  @media (max-width: 767px) {
    padding: 15px 10px;
  }
  
  :deep(.el-tabs__header) {
    @media (max-width: 767px) {
      margin-bottom: 15px;
    }
  }
  
  :deep(.el-tabs__item) {
    @media (max-width: 767px) {
      padding: 0 10px;
      font-size: 14px;
    }
  }
}

/* 个人信息部分 */
.avatar-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  
  @media (max-width: 767px) {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(to right, #3f51b5, #5c6bc0);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  
  @media (max-width: 767px) {
    margin-right: 0;
    margin-bottom: 15px;
  }
}

.user-avatar {
  font-size: 40px;
  color: white;
}

.user-info h2 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #333;
}

.user-status {
  display: flex;
  align-items: center;
  color: #f0b90b;
  font-weight: 500;
}

.premium-icon {
  margin-right: 8px;
}

/* 信息项 */
.info-items {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
  gap: 15px;
  flex-wrap: nowrap;
  
  @media (max-width: 767px) {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px 0;
    gap: 8px;
  }
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  min-width: 120px;
  max-width: 150px;
  font-weight: 500;
  color: #666;
  white-space: nowrap;
  flex-shrink: 0;
  text-align: right;
  
  @media (max-width: 767px) {
    min-width: auto;
    max-width: none;
    margin-bottom: 0;
    white-space: normal;
  }
}

.info-value {
  flex: 1;
  color: #333;
  word-break: break-all;
  min-width: 0;
  
  @media (max-width: 767px) {
    width: 100%;
    margin-bottom: 8px;
  }
}

/* 安全设置部分 */
.security-section {
  padding: 10px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  margin-bottom: 15px;
  
  @media (max-width: 767px) {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
}

.security-info h3 {
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.security-info p {
  color: #666;
  font-size: 14px;
}

/* 弹窗相关样式 */
.responsive-dialog :deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  background-color: #333;
  color: #fff;
  border: 1px solid #444;
}

.responsive-dialog :deep(.el-dialog__header) {
  padding: 15px 20px;
  margin: 0;
  border-bottom: 1px solid #444;
}

.responsive-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.responsive-dialog :deep(.el-dialog__title) {
  word-break: break-word;
  white-space: normal;
  line-height: 1.4;
  font-size: 16px;
  display: inline-block;
  max-width: 100%;
  overflow-wrap: break-word;
  color: #fff;
}

.bind-form {
  padding: 0 10px;
}

@media screen and (max-width: 768px) {
  .bind-form {
    padding: 0 5px;
  }

  .verification-code-group {
    flex-direction: column;
    gap: 10px;
  }

  .verification-code-btn {
    width: 100%;
    margin-left: 0;
  }

  .dialog-footer {
    display: flex;
    flex-direction: column;
    gap: 10px;
  }

  .dialog-footer button {
    width: 100%;
    margin-left: 0 !important;
  }
  
  :deep(.el-form-item__label) {
    line-height: 1.2;
    padding-bottom: 8px;
    word-break: break-word;
    white-space: normal;
    text-align: left;
  }
  
  :deep(.el-form--default .el-form-item) {
    margin-bottom: 22px;
  }
  
  .password-form {
    padding: 10px 0;
  }
  
  .password-form-item {
    margin-bottom: 25px;
  }
  
  .password-dialog-footer {
    margin-top: 30px;
  }
}

.verification-code-group {
  display: flex;
  gap: 10px;
}

.verification-code-btn {
  flex-shrink: 0;
}

.verification-code-btn.cooldown {
  opacity: 0.7;
  cursor: not-allowed;
}

.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 密码表单特定样式 */
.password-form {
  padding: 10px;
}

.password-form-item {
  margin-bottom: 20px;
}

.password-form-item :deep(.el-form-item__label) {
  font-weight: 500;
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 8px;
  word-break: break-word;
  overflow-wrap: break-word;
  hyphens: auto;
  max-width: 100%;
}

.password-input {
  width: 100%;
}

.password-input :deep(.el-input__inner) {
  border-color: #555;
  color: #e0e0e0;
}

.password-input :deep(.el-input__inner:focus) {
  border-color: #1989fa;
}

.password-dialog-footer {
  margin-top: 25px;
}

.password-btn {
  min-width: 100px;
  height: 40px;
  font-size: 14px;
  border-radius: 4px;
}

.cancel-btn {
  background-color: #2c2c2c;
  border-color: #555;
  color: #e0e0e0;
}

.cancel-btn:hover {
  background-color: #3a3a3a;
  border-color: #666;
  color: #fff;
}

.confirm-btn:hover {
  background-color: #40a9ff;
}

.confirm-btn {
  font-weight: 500;
}

/* 询问历史样式 */
.history-section {
  padding: 10px 0;
}

.search-bar {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
  
  @media (max-width: 767px) {
    flex-direction: column;
    gap: 10px;
  }
}

.search-input {
  flex: 1;
}

.history-list {
  background-color: #fff;
  border-radius: 8px;
}

.history-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  transition: background-color 0.2s;
  
  @media (max-width: 767px) {
    padding: 12px 10px;
  }
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-icon {
  width: 48px;
  height: 48px;
  background-color: #f0f2f5;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  color: #409eff;
  font-size: 24px;
  
  @media (max-width: 767px) {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    font-size: 20px;
  }
}

.history-content {
  flex: 1;
}

.history-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #333;
}

.text-red {
  color: #f56c6c;
}

.text-blue {
  color: #409eff;
}

.history-desc {
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.load-more {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.empty-data {
  padding: 40px 0;
  text-align: center;
}
</style>
